<?php

namespace Core\Http;

use Error;

trait RequestValidation
{
    protected $rules = [];

    // 设置参数校验规则
    public function setValidation(string $name, string $message)
    {
        $this->rules[$name] = [
            'message' => $message
        ];
    }

    /**
     * @param sting $key    需要验证的字段, null 验证所有字段
     * @param array $data   需要验证的数据
     */
    public function validated(?string $key, array $data)
    {
        $keys = $key ? [$key] : array_keys($this->rules);

        // 校验数据
        foreach ($keys as $k) {
            if (!array_key_exists($k, $data) || (empty($data[$k]) && $data[$k] != '0')) {
                throw new Error($this->rules[$k]['message']);
            }
        }
    }
}
